/*******************************************************
 * @作者: zhaohua
 * @日期: 2011-9-23
 * @描述: 操作主要数据库的帮助类
 * @声明: copyrights reserved by personal 2007-2011
 *******************************************************/
package com.android.pagemarket.io.database;

import java.io.File;
import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.os.Environment;
import android.util.Log;

import com.android.pagemarket.business.model.Message;
import com.android.pagemarket.business.model.QuotType;
import com.android.pagemarket.business.model.Region;
import com.android.pagemarket.business.model.VersionInfo;
import com.android.pagemarket.business.update.DownloadDao;
import com.android.pagemarket.io.protocol.out.InitInfo;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper
{
	protected static String DB_NAME = "main.db";
	protected static String FILE_SAVE_ROOT = "/pagemarket/";
	
	/** 
	 * 数据库根据新旧版本号的差值dela进行修改数据库
	 * 1.dela < 0  :不向上 兼容, delete
	 * 2.dela == 0 :当前版本不修改
	 * 3.deta == 1 :向后兼容一个版本，alter
	 * 4.deta >1   :无法兼容，delete
	 * */
	private static int version = 12;

	public DatabaseHelper(Context context)
	{
		this(context, getDBPath(context, true, DB_NAME), null, version);
	}

	public DatabaseHelper(Context context, String name, CursorFactory factory, int version)
	{
		super(context, name, factory, version);
	}
	
    @Override
    public void onCreate(SQLiteDatabase db, ConnectionSource source)
    {
        onCreate0(db);
        
        initTable(source);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, ConnectionSource source, int oldVersion, int newVersion)
    {
        onUpgrade0(db,oldVersion,newVersion);
        
        cleanUpDatabase(source);
        initTable(source);
    }
	    
    public void onCreate0(SQLiteDatabase db)
    {
        // 创建表和视图
        initTable(db);        
        // 初始化数据
        initData(db);
    }

    public void onUpgrade0(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        int deta = newVersion - oldVersion;
        
        // 没有变化
        if(deta == 0)
        {
            return;
        }
        
        // 不做向上兼容, 或者 向下无法兼容 , 删除直接修改
        if(deta < 0 || deta > 1 )
        {           
            cleanUpDatabase(db);        
            onCreate0(db);
            return;
        }
        
        // 兼容,修改表       
        if(deta == 1)
        {           
            alterTable(db);
            return;
        }
    }
    
    /** 创建表和视图*/
    private void initTable(SQLiteDatabase db)
    {
        db.execSQL(DownloadDao.CREATE_TABLE);
    }
    
    private void initTable(ConnectionSource source)
    {
        try
        {
            TableUtils.createTable(source, Message.class);
            TableUtils.createTable(source, QuotType.class);
            TableUtils.createTable(source, Region.class);
            TableUtils.createTable(source, VersionInfo.class);
            TableUtils.createTable(source, InitInfo.class);
            
        } catch (SQLException e)
        {
            e.printStackTrace();;
            Log.e("DatabaseHelper", e.getMessage());
        }
    }
    
    /** 更新修改表*/
    private void alterTable(SQLiteDatabase db)
    {
        
    }
    
    /** 初始化数据*/
    private void initData(SQLiteDatabase db)
    {       

    }
    
    /** 删除表 */
    private void cleanUpDatabase(SQLiteDatabase db)
    {
        db.execSQL(DownloadDao.DROP_TABLE);
    }
    
    /** 删除表 */
    private void cleanUpDatabase(ConnectionSource source)
    {
        try
        {
            TableUtils.dropTable(source, Message.class, true);
            TableUtils.dropTable(source, QuotType.class, true);
            TableUtils.dropTable(source, Region.class, true);
            TableUtils.dropTable(source, VersionInfo.class, true);
            TableUtils.dropTable(source, InitInfo.class, true);
        } catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

	/**
	 * 获取数据库的存放路径，策略为
	 * 1.有卡，则主DB存放在应用程序的目录下，辅DB防止卡的目录下。
	 * 2.无卡，则主辅DB都放在应用程序目录下。
	 * @return
	 */
	public static String getDBPath(Context context, boolean mainAble, String dbName)
	{
		// 2.2 之前的版本 数据库不能传路径
		if(android.os.Build.VERSION.SDK_INT < 8)
		{
			return dbName;
		}
		if(Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
		{
			// 有卡
			if(mainAble)
			{
				return context.getDatabasePath(dbName).getAbsolutePath();
			}else
			{
				String path = Environment.getExternalStorageDirectory().getAbsolutePath();
				path += FILE_SAVE_ROOT + "databases/";
				
				File dir = new File(path);
				if (!dir.exists())
				{
					if (!dir.mkdirs())
					{
						Log.e("dbhelper", "--->create databases dir fail!");
						return null;
					}
				}
				return path + dbName;
			}
		}else
		{
			// 无卡
			return context.getDatabasePath(dbName).getAbsolutePath();
		}
	}

	////////////////////////////////////////////////////////////////////////////////////
	private Dao<InitInfo, Integer> mInitInfoDao;	
	public Dao<InitInfo, Integer> getInitInfoDao()
	{
	  if(mInitInfoDao == null)
	  {
    	    try
            {
                mInitInfoDao = getDao(InitInfo.class);
            } catch (SQLException e)
            {
                e.printStackTrace();
            }
	  }
	  return mInitInfoDao;
	}
	
	private Dao<VersionInfo, Integer> mVersionInfoDao;   
    public Dao<VersionInfo, Integer> getVersionInfoDao()
    {
      if(mVersionInfoDao == null)
      {
            try
            {
                mVersionInfoDao = getDao(VersionInfo.class);
            } catch (SQLException e)
            {
                e.printStackTrace();
            }
      }
      return mVersionInfoDao;
    }
    
    private Dao<Message, Integer> mMessageDao;   
    public Dao<Message, Integer> getMessageDao()
    {
      if(mMessageDao == null)
      {
            try
            {
                mMessageDao = getDao(Message.class);
            } catch (SQLException e)
            {
                e.printStackTrace();
            }
      }
      return mMessageDao;
    }
    
    private Dao<QuotType, Integer> mQuotDao;   
    public Dao<QuotType, Integer> getQuotDao()
    {
      if(mQuotDao == null)
      {
            try
            {
                mQuotDao = getDao(QuotType.class);
            } catch (SQLException e)
            {
                e.printStackTrace();
            }
      }
      return mQuotDao;
    }
    
    private Dao<Region, Integer> mRegionDao;   
    public Dao<Region, Integer> getRegionDao()
    {
      if(mRegionDao == null)
      {
            try
            {
                mRegionDao = getDao(Region.class);
            } catch (SQLException e)
            {
                e.printStackTrace();
            }
      }
      return mRegionDao;
    }   
	////////////////////////////////////////////////////////////////////////////////////
}
